$(document).ready(function() {
	
	$("form").submit(function(e){
		e.preventDefault();
		return login();
	});
	
});

var isRegistering = false;

/**
 * Executes the login functionality
 * @returns true if successful, false otherwise
 * 
 */
function login(){
	var username = $("#username").val();
	var password = $("#password").val();
	
	//check for username password length
	if(!username.trim()){
		displayErrorMessage("Please enter a username!");
		return;
	}
	
	if(!password.trim()){
		displayErrorMessage("Please enter a password!");
		return;
	}
	
	
	if(isRegistering){
		//Make the call to check if this username is valid
		
		var funcRegister = function(data, status){
			console.log(data);
			//If an error occurred, output the error
			if(data.code == "ERROR"){
				displayErrorMessage(data.message);
			} else if(data.code == "SUCCESS"){
				//TODO redirect to home page
				document.location.href = "home.php";
			}
		};
		
		loginAjaxRequest(username, password, "backend/register.php", funcRegister);
		
	} else {
		//Make the call to login
		
		var funcRegister = function(data, status){
			console.log(data);
			//If an error occurred, output the error
			if(data.code == "ERROR"){
				displayErrorMessage(data.message);
			} else if(data.code == "SUCCESS"){
				//TODO redirect to home page
				document.location.href = "home.php";
			}
		};
		
		loginAjaxRequest(username, password, "backend/login.php", funcRegister);
	}
	
	
	return false;
}

function beginRegistration(){
	isRegistering = !isRegistering;
	
	if(isRegistering){
		$("#login_submit").val("Register");
		$("#login_register").val("Cancel");
	} else {
		$("#login_submit").val("Login");
		$("#login_register").val("Register");
		
	}
}

function loginAjaxRequest(username, password, strURL, funcCallBack){
	$.ajax({
		url: strURL,
		type: 'post',
		data: {'username': username, 'password': password},
		success: funcCallBack,
		error: function(xhr, desc, err){
			console.log(xhr);
	        console.log("Details: " + desc + "\nError:" + err);
		}
	});
}

function displayErrorMessage(message){
	$("#error_message").text(message);
	
}